<?php
ob_start();
require_once('FirePHPCore/FirePHP.class.php');

function connect_db() {
	$con = mysql_connect ( "localhost", "root", "" );
	if (! $con) {
		die ( 'Could not connect: ' . mysql_error () );
	}
	if (! mysql_query ( "use dh", $con )) {
		die ( 'Could not use database ' . mysql_error () );
	}
	return $con;
}
function getAllBlocks() {
	$con = connect_db ();
	$sql = "select blockid, blockname from BLOCK";
	$result = eatResult ( mysql_query ( $sql, $con ) );
	mysql_close ( $con );
	return $result;
}
function getAllCrops() {
	$con = connect_db ();
	$sql = "select * from CROP order by cropname";
	$result = eatResult ( mysql_query ( $sql, $con ) );
	mysql_close ( $con );
	return $result;
}
function getAllUsers() {
	$con = connect_db ();
	$sql = "select * from USER order by username";
	$result = eatResult ( mysql_query ( $sql, $con ) );
	mysql_close ( $con );
	return $result;
}
function getAllUnits() {
	$con = connect_db ();
	$sql = "select * from UNIT order by unitname";
	$result = eatResult ( mysql_query ( $sql, $con ) );
	mysql_close ( $con );
	return $result;
}
function getAllUnitsWithoutOrder() {
	$con = connect_db ();
	$sql = "select * from UNIT";
	$result = eatResult ( mysql_query ( $sql, $con ) );
	mysql_close ( $con );
	return $result;
}

function getAllCategories() {
	$con = connect_db ();
	$sql = "select * from CATEGORY order by categoryname";
	$result = eatResult ( mysql_query ( $sql, $con ) );
	mysql_close ( $con );
	return $result;
}
function getAllCustomers() {
	$con = connect_db ();
	$sql = "select * from CUSTOMER";
	$result = eatResult ( mysql_query ( $sql, $con ) );
	mysql_close ( $con );
	return $result;
}
function getDonationCustomers() {
	$con = connect_db ();
	$sql = "select * from CUSTOMER where customerType='1'";
	$result = eatResult ( mysql_query ( $sql, $con ) );
	mysql_close ( $con );
	return $result;
}
function getSalesCustomers() {
	$con = connect_db ();
	$sql = "select * from CUSTOMER where customerType='0'";
	$result = eatResult ( mysql_query ( $sql, $con ) );
	mysql_close ( $con );
	return $result;
}
function getCategory($categoryid) {
	if ($categoryid == null)
		die ( "No categoryid specified" );
	$con = connect_db ();
	$categoryid = mysql_real_escape_string ( $categoryid );
	$sql = "select * from CATEGORY where categoryid=$categoryid";
	$result = eatResult ( mysql_query ( $sql, $con ) );
	mysql_close ( $con );
	if (count ( $result ) < 1)
		die ( "No category with categoryid=$categoryid found" );
	return $result [0];
}
function getCropId($cropname) {
	$con = connect_db ();
	$sql = "select * from CROP 
			where cropname = '$cropname'";
	$count = mysql_num_rows ( mysql_query ( $sql, $con ) );
	if ($count == 0) {
		echo "No such cropname in record!";
		return 0;
	}
	$result = eatResult ( mysql_query ( $sql, $con ) );
	mysql_close ( $con );
	return $result [0] ['cropid'];
}
function getCategoryId($categoryname) {
	$con = connect_db ();
	$sql = "select * from CATEGORY 
			where categoryname = '$categoryname'";
	$count = mysql_num_rows ( mysql_query ( $sql, $con ) );
	if ($count == 0) {
		echo "<script type='text/javascript'>alert('No such category name in record!')</script>";
		//echo "No such category name in record!";
		return 0;
	}
	$result = eatResult ( mysql_query ( $sql, $con ) );
	mysql_close ( $con );
	return $result [0] ['categoryid'];
}

function addCrop($cropname, $firstunit, $secondunit, $categoryid) {
	
	$con = connect_db ();
	$sql = "select * from CROP where cropname='$cropname'";
	$result = eatResult ( mysql_query ( $sql, $con ) );
	if (count ( $result ) >= 1) {
		//echo "existing crop";
		echo "<script type=\"text/javascript\">window.alert(\"existing crop\")</script>"; 		
		return;
	}
	
	if ($secondunit == 0){
	$sql = "insert into CROP 
		(cropname, firstUnit, categoryid) values
		('$cropname', '$firstunit', '$categoryid')";
	}
	else{
	$sql = "insert into CROP 
		(cropname, firstUnit, secondUnit, categoryid) values
		('$cropname', '$firstunit', '$secondunit', '$categoryid')";
	}



	if (mysql_query ( $sql, $con )) {
		//echo "<script type='text/javascript'>alert('New crop $cropname has been added to category $categoryid ')</script>";
		//echo "<h3>New crop <em>$cropname</em> has been added to category $categoryid </h3>";
		echo "<script type=\"text/javascript\">window.alert(\"New crop $cropname has been added to category $categoryid\")</script>"; 		
	} else {
		echo "<script type='text/javascript'>alert('Adding new crop failed!')</script>";
		//echo "Adding new crop failed!";
	}
	mysql_close ( $con );
}

function getCategoryNameId($categoryid) {
	$con = connect_db ();
	$sql = "select * from CATEGORY 
			where categoryid = '$categoryid'";
	$count = mysql_num_rows ( mysql_query ( $sql, $con ) );
	if ($count == 0) {
		//echo "<script type='text/javascript'>alert('No such category name in record!')</script>";
		//echo "No such category name in record!";
		return 0;
	}
	$result = eatResult ( mysql_query ( $sql, $con ) );
	mysql_close ( $con );
	return $result [0] ['categoryname'];
}

function getCustomerId($customerName) {
	if ($customerName == 'all') return NULL; //if 'all', then return NULL so the data grabbing functions will get data for all customers
	$con = connect_db ();
	$sql = "select * from CUSTOMER 
			where customername='$customerName'";
	$count = mysql_num_rows ( mysql_query ( $sql, $con ) );
	if ($count == 0) {
		echo "No such customer in record!";
		return 0;
	}
	$result = eatResult ( mysql_query ( $sql, $con ) );
	mysql_close ( $con );
	return $result [0] ['customerid'];
}
function getUnitId($unitName) {
	$con = connect_db ();
	$sql = "select * from UNIT
			where unitname='$unitName'";
	$count = mysql_num_rows ( mysql_query ( $sql, $con ) );
	if ($count == 0) {
		echo "No such unit in record!";
		return 0;
	}
	$result = eatResult ( mysql_query ( $sql, $con ) );
	mysql_close ( $con );
	return $result [0] ['unitid'];
}

function getCropIds($crops) {
	$result = array ();
	foreach ( $crops as $crop ) {
		$result [] = getCropId ( $crop );
	}
	return $result;

}

function updateCrop($cropid, $cropname, $season, $notes, $categoryid) {
	if ($cropid == null)
		die ( "No cropid specified" );
	$con = connect_db ();
	
	$sql = "update CROP
			SET	cropname=$cropname,
				season=$season,
				notes=$notes,
				categoryid=$categoryid
			WHERE	cropid=$cropid";
	
	if (mysql_query ( $sql, $con )) {
		echo 'update ok!';
	} else {
		echo 'update failed.';
	}
	mysql_close ( $con );
}

function getCrop($cropid) {
	if ($cropid == null)
		die ( "No cropid specified" );
	$con = connect_db ();
	$cropid = mysql_real_escape_string ( $cropid );
	$sql = "select * from CROP where CROP.cropid=$cropid";
	$result = eatResult ( mysql_query ( $sql, $con ) );
	mysql_close ( $con );
	if (count ( $result ) < 1)
		die ( "No crop with cropid=$cropid found" );
	
	return $result [0];
}

function getCategoryBySuccessor($successorId) {
	$con = connect_db ();
	$sql = "select * from CATEGORY where successor1=$successorId";
	$result = eatResult ( mysql_query ( $sql, $con ) );
	mysql_close ( $con );
	return $result;
}

function getPrintCategory() {
	$con = connect_db ();
	$sql = "select categoryid, categoryname, successor from CATEGORY";
	$result = mysql_query ( $sql, $con );
	mysql_close ( $con );
	return $result;
}

function getCategoryOrderSuccessor() {
	$con = connect_db ();
	$sql = "select categoryname from CATEGORY order by successor";
	$result = eatResult ( mysql_query ( $sql, $con ) );
	mysql_close ( $con );
	return $result;
}

function getCategorySuccessor() {
	$con = connect_db ();
	$sql = "select successor from CATEGORY";
	$result = eatResult ( mysql_query ( $sql, $con ) );
	mysql_close ( $con );
	return $result;
}

function EditSuccessor($categoryone, $categorytwo) {
	$con = connect_db ();
	$sql = "update CATEGORY SET successor =$categorytwo where categoryid =$categoryone";
	mysql_query ( $sql, $con );
	echo "<script type=\"text/javascript\">window.alert(\"Rotation plan changed.\")</script>"; 		
	mysql_close ( $con );
}
function addCategory($categoryname, $notes) {
	$con = connect_db ();
	$sql = "select * from CATEGORY where categoryname='$categoryname'";
	$result = eatResult ( mysql_query ( $sql, $con ) );
	if (count ( $result ) >= 1) {
	echo "<script type=\"text/javascript\">window.alert(\"existing category\")</script>"; 		
		return;
	}
	$sql = "insert into CATEGORY 
			(categoryname, notes, successor) values
			('$categoryname', '$notes', null)";
	if (mysql_query ( $sql, $con )) {
		echo "<script type=\"text/javascript\">window.alert(\"New category $categoryname added!\")</script>"; 		
	} else {
		echo "<script type=\"text/javascript\">window.alert(\"New category $categoryname failed!\")</script>"; 		
	}
	mysql_close ( $con );
}

function addUser($username, $password) {
	$con = connect_db ();
	$temp = md5 ( $password );
	
	$sql = "select * from USER where username='$username'";
	$result = eatResult ( mysql_query ( $sql, $con ) );
	if (count ( $result ) >= 1) {
		echo "<script type=\"text/javascript\">window.alert(\"The username $username is already existed, please try another username.\")</script>"; 	
		//echo "<h3>The username <em>$username</em> is already existed, please try another username.</h3>";
		return;
	}
	$sql = "Insert into USER 
		(username, password) 
		values('$username','$temp')";
	if (mysql_query ( $sql, $con )) {
		echo "<script type=\"text/javascript\">window.alert(\"The following account has been successfully registered .Username: $username\")</script>"; 	
		//echo "<h3>The following account has been successfully registered .<br />Username: $username<br></h3>";
	} else {
		echo "<script type=\"text/javascript\">window.alert(\"registration failed!\")</script>"; 	
		//echo "reg failed!";
	}
	mysql_close ( $con );
}

function updateCategory($categoryid, $categoryname, $notes) {
	if ($categoryid == null)
		die ( "No categoryid specified" );
	$con = connect_db ();
	
	$sql = "update CATEGORY
			SET	categoryname=$categoryname,
				notes=$notes
			WHERE	categoryid=$categoryid";
	
	if (mysql_query ( $sql, $con )) {
		echo 'update ok!';
	} else {
		echo 'update failed.';
	}
	mysql_close ( $con );
}
function deleteCategory($categoryname) {
	$con = connect_db ();
	
	$sql = "delete from CATEGORY 
			where categoryname='$categoryname'";
	
	if (mysql_query ( $sql, $con )) {
		echo "<script type=\"text/javascript\">window.alert(\"Category $categoryname deleted!\")</script>"; 	
		//echo "<h3>Category <em>$categoryname</em> deleted!</h3>";
	} else {
		echo "<script type=\"text/javascript\">window.alert(\"delete failed.\")</script>"; 	
		//echo '<h3>delete failed.</h3>';
	}
	mysql_close ( $con );
}
function deleteUser($users) {
	$con = connect_db ();
	
	$sql = "delete from USER 
			where username='$users'";
	
	if (mysql_query ( $sql, $con )) {
		echo "<script type=\"text/javascript\">window.alert(\"The account for $users has been deleted\")</script>"; 	
		//echo "<h3>The account for $users has been deleted</h3>";
	} else {
		echo "<script type=\"text/javascript\">window.alert(\"Delete failed.\")</script>"; 	
		//echo "<h3>Delete failed.</3>";
	}
	mysql_close ( $con );
}
function deleteCrop($cropname) {
	$con = connect_db ();
	
	$sql = "delete from CROP 
			where cropname='$cropname'";
	
	if (mysql_query ( $sql, $con )) {
		echo "<script type=\"text/javascript\">window.alert(\"Crop $cropname deleted!\")</script>";
		//echo "<h3>Crop <em>$cropname</em> deleted!</h3>";
	} else {
		echo "<script type=\"text/javascript\">window.alert(\"delete failed.!\")</script>";
		//echo "<h3>delete failed.</h3>";
	}
	mysql_close ( $con );
}
/**
 * Get unitname by unitid.
 * Return null if not applicable.
 */
function getUnitName($unitid) {
	$con = connect_db ();
	if ($unitid == null) {
		return null;
	}
	$sql = "select * from UNIT where unitid='$unitid'";
	$result = eatResult ( mysql_query ( $sql, $con ) );
	if (count ( $result ) == 0) {
		return null;
	}
	mysql_close ( $con );
	$name = $result [0] ['unitname'];
	return $name;
}
/**
 * Give cropname, return up to 2 unitnames in arr[0] and arr[1]. 
 * arr[1] is possibly null.
 */
function getUnitsByCropname($cropname) {
	$con = connect_db ();
	$sql = "select * from CROP where cropname='$cropname'";
	$result = eatResult ( mysql_query ( $sql, $con ) );
	mysql_close ( $con );
	$array [0] = getUnitName ( $result [0] ['firstUnit'] );
	$array [1] = getUnitName ( $result [0] ['secondUnit'] );
	return $array;
}

function eatResult($resource) {
	$result = array ();
	if ($resource) {
		$next = mysql_fetch_assoc ( $resource );
		while ( $next != false ) {
			$result [] = $next;
			$next = mysql_fetch_assoc ( $resource );
		}
	}
	return $result;
}
/** 
 * Return the day of the first saturday of a year,</br>
 * with 0 being the first day of the year.
 * @param $year
 * four digit year
 * @return
 * The day of the first saturday of the year.
 */
function getFirstSat($year) {
	$firstDOW = date ( "D", strtotime ( "$year-01-01" ) );
	if ($firstDOW == 'Sun')
		return 6;
	if ($firstDOW == 'Mon')
		return 5;
	if ($firstDOW == 'Tue')
		return 4;
	if ($firstDOW == 'Wed')
		return 3;
	if ($firstDOW == 'Thu')
		return 2;
	if ($firstDOW == 'Fri')
		return 1;
	return 0;
}
/**
 * Get week number for a certain date.
 * @param $mysqlDay
 * date in mysql database
 * @param $firstSat
 * firstSaturday in the year
 * @return
 * week number for a certain date</br>
 * Week number starts from 0.
 */
function getWeekNumber($mysqlDay, $firstSat) {
	$day = date ( "z", strtotime ( $mysqlDay ) );
	$day += (6 - $firstSat);
	return ( int ) ($day / 7);
}
/**
 * Return a string describe days in a week.</br>
 * Except the 0th week, a week starts from Sunday and ends at Saturday.</br>
 * The 0th week starts at 01/01 of the year, ends at the nearest Saturday.</br>
 * 
 * @param $weekNumber
 * week number, start from 0
 * @param $year
 * four digit year
 * @return
 * A string formatted as mm/dd - mm/dd, showing the week's time range.
 */
function getWeekString($weekNumber, $year) {
	$firstSat = getFirstSat ( $year );
	if ($weekNumber == 0) {
		return "01/01 - 01/0" . ($firstSat + 1);
	}
	$start = (($weekNumber - 1) * 7) + $firstSat;
	$end = $start + 5;
	$startDay = date_create("01/01/$year");
	date_modify($startDay, "+$start day");
	$endDay = date_create("01/01/$year");
	date_modify($endDay, "+$end day");
	return $startDay->format ( "m/d" ) . " - " . $endDay->format ( "m/d" );
}
/**
 * Get all harvests in a given range of time.
 *
 * @param date $startTime 
 * If null, the beginning of the range is not constrained
 * @param date $endTime 
 * If null, the end of the range is not constrained
 * @param int $cropid 
 * If null, return all crops
 * @param int $unitid 
 * If null, return all units
 */
function getHarvests($startTime, $endTime, $cropid, $unitid) {
	$con = connect_db ();
	$sql = rangeQueryHarvest ( $startTime, $endTime, $cropid, $unitid );
	$result = eatResult ( mysql_query ( $sql, $con ) );
	mysql_close ( $con );
	return $result;
}
function rangeQueryHarvest($startTime, $endTime, $cropid, $unitid) {
	$startTime = strtotime ( $startTime );
	$startTime = date ( 'Y-m-d', $startTime );
	$endTime = strtotime ( $endTime );
	$endTime = date ( 'Y-m-d', $endTime );
	$sql = "select * from AMOUNT_HARVESTED ";
	$where = "WHERE";
	if ($startTime != null) {
		$sql = "$sql $where DATEDIFF(startDate, '$startTime') >= 0 ";
		$where = "AND";
	}
	if ($endTime != null) {
		$sql = "$sql $where DATEDIFF(startDate, '$endTime') <= 0 ";
		$where = "AND";
	}
	if ($cropid != null) {
		$sql = "$sql $where cropid = $cropid";
	}
	if ($unitid != null) {
		$sql = "$sql $where unitid = $unitid";
	}
	return $sql;
}
/*
 * Get all seed purchases in a given range of time.
 *
 * @param date $startTime earliest time in the range. If null, the beginning of the range is not constrained
 * @param date $endTime latest time in the range. If null, the end of the range is not constrained
 * @param int $cropid crop whose seed purchases to return. If null, return purchases for all crops
 */
function getSeedPurchases($startTime, $endTime, $cropid) {
	$con = connect_db ();
	$sql = rangeQuery ( $startTime, $endTime, $cropid, "SEEDS_PURCHASED" );
	$result = eatResult ( mysql_query ( $sql, $con ) );
	mysql_close ( $con );
	return $result;
}
/*
 * Get all plants added in a given range of time.
 *
 * @param date $startTime earliest time in the range. If null, the beginning of the range is not constrained
 * @param date $endTime latest time in the range. If null, the end of the range is not constrained
 * @param int $cropid crop whose seed purchases to return. If null, return purchases for all crops
 */
function getPlantsAdded($startTime, $endTime, $cropid) {
	$con = connect_db ();
	$sql = rangeQuery ( $startTime, $endTime, $cropid, "PLANTS_ADDED" );
	$result = eatResult ( mysql_query ( $sql, $con ) );
	mysql_close ( $con );
	return $result;
}
function getPlantsTransplanted($startTime, $endTime, $cropid) {
	$con = connect_db ();
	$sql = rangeQuery ( $startTime, $endTime, $cropid, "PLANTS_TRANSPLANTED" );
	$result = eatResult ( mysql_query ( $sql, $con ) );
	mysql_close ( $con );
	return $result;
}
/**
 * Get all sales in a given range of time.
 * @param date $startTime 
 * If null, the beginning of the range is not constrained
 * @param date $endTime 
 * If null, the end of the range is not constrained
 * @param int $cropid 
 * If null, return for all crops
 * @param int $unitid
 * If null, return for all units
 * @param int $customerid
 * If null, return for all customers
 */
function getSales($startTime, $endTime, $cropid, $unitid, $customerid) {
	$con = connect_db ();
	$sql = rangeQuerySales ( $startTime, $endTime, $cropid, $unitid, $customerid );
	$result = eatResult ( mysql_query ( $sql, $con ) );
	mysql_close ( $con );
	return $result;
}
function rangeQuerySales($startTime, $endTime, $cropid, $unitid, $customerid) {
	$startTime = strtotime ( $startTime );
	$startTime = date ( 'Y-m-d', $startTime );
	$endTime = strtotime ( $endTime );
	$endTime = date ( 'Y-m-d', $endTime );
	$sql = "select * from AMOUNT_SOLD_DONATED ";
	$where = "WHERE";
	if ($startTime != null) {
		$sql = "$sql $where DATEDIFF(startDate, '$startTime') >= 0 ";
		$where = "AND";
	}
	if ($endTime != null) {
		$sql = "$sql $where DATEDIFF(startDate, '$endTime') <= 0 ";
		$where = "AND";
	}
	if ($cropid != null) {
		$sql = "$sql $where cropid = $cropid";
	}
	if ($unitid != null) {
		$sql = "$sql $where unitid = $unitid";
	}
	if ($customerid != null) {
		$sql = "$sql $where customerid = $customerid";
	}
	$sql = "$sql $where sdType = '0'";
	return $sql;
}

/**
 * Get all donation in a given range of time.
 * @param date $startTime 
 * If null, the beginning of the range is not constrained
 * @param date $endTime 
 * If null, the end of the range is not constrained
 * @param int $cropid 
 * If null, return for all crops
 * @param int $unitid
 * If null, return for all units
 * @param int $customerid
 * If null, return for all customers
 */
function getDonation($startTime, $endTime, $cropid, $unitid, $customerid) {
	$con = connect_db ();
	$sql = rangeQueryDonation ( $startTime, $endTime, $cropid, $unitid, $customerid );
	$result = eatResult ( mysql_query ( $sql, $con ) );
	mysql_close ( $con );
	return $result;
}
function rangeQueryDonation($startTime, $endTime, $cropid, $unitid, $customerid) {
	$startTime = strtotime ( $startTime );
	$startTime = date ( 'Y-m-d', $startTime );
	$endTime = strtotime ( $endTime );
	$endTime = date ( 'Y-m-d', $endTime );
	$sql = "select * from AMOUNT_SOLD_DONATED ";
	$where = "WHERE";
	if ($startTime != null) {
		$sql = "$sql $where DATEDIFF(startDate, '$startTime') >= 0 ";
		$where = "AND";
	}
	if ($endTime != null) {
		$sql = "$sql $where DATEDIFF(startDate, '$endTime') <= 0 ";
		$where = "AND";
	}
	if ($cropid != null) {
		$sql = "$sql $where cropid = $cropid";
	}
	if ($unitid != null) {
		$sql = "$sql $where unitid = $unitid";
	}
	if ($customerid != null) {
		$sql = "$sql $where customerid = $customerid";
	}
	$sql = "$sql $where sdType = '1'";
	return $sql;
}

function rangeQuery($startTime, $endTime, $cropid, $tableName, $colName = "startDate") {
	$startTime = strtotime ( $startTime );
	$startTime = date ( 'Y-m-d', $startTime );
	$endTime = strtotime ( $endTime );
	$endTime = date ( 'Y-m-d', $endTime );
	$sql = "select * from $tableName ";
	$where = "WHERE";
	if ($startTime != null) {
		$sql = "$sql $where DATEDIFF($colName, '$startTime') >= 0 ";
		$where = "AND";
	}
	if ($endTime != null) {
		$sql = "$sql $where DATEDIFF($colName, '$endTime') <= 0 ";
		$where = "AND";
	}
	if ($cropid != null) {
		$sql = "$sql $where cropid = $cropid";
	}
	return $sql;
}
function mySort($arr) {
	$result = array ();
	$keys = array_keys ( $arr );
	asort ( $keys );
	foreach ( $keys as $key ) {
		$result [$key] = $arr [$key];
	}
	return $result;
}

/**
 * Get general crop data within a year.
 * 
 * @param $year
 * four digit year
 * @param $cropId
 * @return
 * an array: $result[Type].
 * Type can be 'seed_purchased', 'planted', 'transplanted'.
 * Zero if no record.
 */
function getGeneralYearlyCropData($cropId, $year) {
	$startTime = "$year-01-01";
	$endTime = "$year-12-31";
	$seedPurchases = getSeedPurchases ( $startTime, $endTime, $cropId );
	$plantsAdded = getPlantsAdded ( $startTime, $endTime, $cropId );
	$plantsTransplanted = getPlantsTransplanted ( $startTime, $endTime, $cropId );
	$result = array ('seedPurchases' => 0, 'plantsAdded' => 0, 'plantsTransplanted' => 0 );
	foreach ( $seedPurchases as $s ) {
		$result ['seedPurchases'] += $s ['quantity'];
	}
	foreach ( $plantsAdded as $p ) {
		$result ['plantsAdded'] += $p ['quantity'];
	}
	foreach ( $plantsTransplanted as $p ) {
		$result ['plantsTransplanted'] += $p ['quantity'];
	}
	return $result;
}

function getHarvestYearlyCropData($cropid, $year, $unitid) {
	$result = 0;
	$startTime = "$year-01-01";
	$endTime = "$year-12-31";
	$harvest = getHarvests ( $startTime, $endTime, $cropid, $unitid );
	foreach ( $harvest as $h ) {
		$result += $h ['quantity'];
	}
	return $result;
}
function getSalesYearlyCropData($cropid, $year, $unitid, $customerid) {
	$result = 0;
	$startTime = "$year-01-01";
	$endTime = "$year-12-31";
	$sales = getSales ( $startTime, $endTime, $cropid, $unitid, $customerid );
	foreach ( $sales as $s ) {
		$result += $s ['quantity'];
	}
	return $result;
}
function getDonationYearlyCropData($cropid, $year, $unitid, $customerid) {
	$result = 0;
	$startTime = "$year-01-01";
	$endTime = "$year-12-31";
	$donation = getDonation ( $startTime, $endTime, $cropid, $unitid, $customerid );
	foreach ( $donation as $d ) {
		$result += $d ['quantity'];
	}
	return $result;
}

/**
 * Get multi year data
 * attr = 's' or 'p' or 't', representing seeds_bought/planted/transplanted
 */
function getGeneralMultiYearCropData($startTime, $endTime, $cropId, $attr) {
	$startYear = intval ( substr ( $startTime, 0, 4 ) );
	$endYear = intval ( substr ( $endTime, 0, 4 ) );
	$result = array ();
	if ($attr == 's') {
		$seedPurchases = getSeedPurchases ( $startTime, $endTime, $cropId );
		foreach ( $seedPurchases as $s ) {
			$year = substr ( $s ['startDate'], 0, 4 );
			if (isset ( $result [$year] )) {
				$result [$year] += $s ['quantity'];
			} else {
				$result [$year] = $s ['quantity'];
			}
		}
	} elseif ($attr == 'p') {
		$plantsAdded = getPlantsAdded ( $startTime, $endTime, $cropId );
		foreach ( $plantsAdded as $p ) {
			$year = substr ( $p ['startDate'], 0, 4 );
			if (isset ( $result [$year] )) {
				$result [$year] += $p ['quantity'];
			} else {
				$result [$year] = $p ['quantity'];
			}
		}
	} elseif ($attr == 't') {
		$plantsTransplanted = getPlantsTransplanted ( $startTime, $endTime, $cropId );
		foreach ( $plantsTransplanted as $p ) {
			$year = substr ( $p ['startDate'], 0, 4 );
			if (isset ( $result [$year] )) {
				$result [$year] += $p ['quantity'];
			} else {
				$result [$year] = $p ['quantity'];
			}
		}
	}
	return $result;
}

function getHarvestMultiYearCropData($startTime, $endTime, $cropid, $unitid) {
	$startYear = intval ( substr ( $startTime, 0, 4 ) );
	$endYear = intval ( substr ( $endTime, 0, 4 ) );
	$result = array ();
	$ans = getHarvests ( $startTime, $endTime, $cropid, $unitid );
	foreach ( $ans as $s ) {
		$year = substr ( $s ['startDate'], 0, 4 );
		if (isset ( $result [$year] )) {
			$result [$year] += $s ['quantity'];
		} else {
			$result [$year] = $s ['quantity'];
		}
	}
	return $result;
}
function getSalesMultiYearCropData($startTime, $endTime, $cropid, $unitid, $customerid) {
	$startYear = intval ( substr ( $startTime, 0, 4 ) );
	$endYear = intval ( substr ( $endTime, 0, 4 ) );
	$result = array ();
	$ans = getSales ( $startTime, $endTime, $cropid, $unitid, $customerid );
	foreach ( $ans as $s ) {
		$year = substr ( $s ['startDate'], 0, 4 );
		if (isset ( $result [$year] )) {
			$result [$year] += $s ['quantity'];
		} else {
			$result [$year] = $s ['quantity'];
		}
	}
	return $result;
}
function getDonationMultiYearCropData($startTime, $endTime, $cropid, $unitid, $customerid) {
	$startYear = intval ( substr ( $startTime, 0, 4 ) );
	$endYear = intval ( substr ( $endTime, 0, 4 ) );
	$result = array ();
	$ans = getDonation ( $startTime, $endTime, $cropid, $unitid, $customerid );
	foreach ( $ans as $s ) {
		$year = substr ( $s ['startDate'], 0, 4 );
		if (isset ( $result [$year] )) {
			$result [$year] += $s ['quantity'];
		} else {
			$result [$year] = $s ['quantity'];
		}
	}
	return $result;
}
/**
 * Greg:
 * Returns a single value for the given crop and given attribute for a particular range whose start and end dates MUST occur within the same calendar year
 * @param $attr
 * 's' or 'p' or 't', representing seedsbought, planted, transplanted
 */
function getGeneralRangeData($startTime, $endTime, $cropId, $attr) {
	if (intVal ( substr ( $startTime, 0, 4 ) ) == intVal ( substr ( $endTime, 0, 4 ) )) {
		$result = getGeneralMultiYearCropData ( $startTime, $endTime, $cropId, $attr );
		foreach ( $result as $year => $data ) {
			return $data; //foreach loop will only run once becuase of this return, and also because the startTime and endTime should be within a particular year
		}
	} else {
		throw new Exception ( "getRangeData function was passed two dates that are not within the same calendar year" );
	}
}
function getHarvestRangeData($startTime, $endTime, $cropid, $unitid) {
	if (intVal ( substr ( $startTime, 0, 4 ) ) == intVal ( substr ( $endTime, 0, 4 ) )) {
		$result = getHarvestMultiYearCropData ( $startTime, $endTime, $cropid, $unitid );
		foreach ( $result as $year => $data ) {
			return $data; //foreach loop will only run once becuase of this return, and also because the startTime and endTime should be within a particular year
		}
	} else {
		throw new Exception ( "getRangeData function was passed two dates that are not within the same calendar year" );
	}
}
function getSalesRangeData($startTime, $endTime, $cropid, $unitid, $customerid) {
	if (intVal ( substr ( $startTime, 0, 4 ) ) == intVal ( substr ( $endTime, 0, 4 ) )) {
		$result = getSalesMultiYearCropData ( $startTime, $endTime, $cropid, $unitid, $customerid );
		foreach ( $result as $year => $data ) {
			return $data; //foreach loop will only run once becuase of this return, and also because the startTime and endTime should be within a particular year
		}
	} else {
		throw new Exception ( "getRangeData function was passed two dates that are not within the same calendar year" );
	}
}
function getDonationRangeData($startTime, $endTime, $cropid, $unitid, $customerid) {
	if (intVal ( substr ( $startTime, 0, 4 ) ) == intVal ( substr ( $endTime, 0, 4 ) )) {
		$result = getDonationMultiYearCropData ( $startTime, $endTime, $cropid, $unitid, $customerid );
		foreach ( $result as $year => $data ) {
			return $data; //foreach loop will only run once becuase of this return, and also because the startTime and endTime should be within a particular year
		}
	} else {
		throw new Exception ( "getRangeData function was passed two dates that are not within the same calendar year" );
	}
}
/**
 * Get daily Crop data within a period of time.
 * attr = 's' or 'p' or 't', representing seeds_bought / planted / transplanted  
 * @return
 * An array $result[Date] => quantity.
 */
function getGeneralDailyCropData($startTime, $endTime, $cropId, $attr) {
	$result = array ();
	if ($attr == 's') {
		$seedPurchases = getSeedPurchases ( $startTime, $endTime, $cropId );
		foreach ( $seedPurchases as $s ) {
			if (isset ( $result [$s ['startDate']] )) {
				$result [$s ['startDate']] += $s ['quantity'];
			} else {
				$result [$s ['startDate']] = $s ['quantity'];
			}
		}
	} else if ($attr == 'p') {
		$plantsAdded = getPlantsAdded ( $startTime, $endTime, $cropId );
		foreach ( $plantsAdded as $p ) {
			if (isset ( $result [$p ['startDate']] )) {
				$result [$p ['startDate']] += $p ['quantity'];
			} else {
				$result [$p ['startDate']] = $p ['quantity'];
			}
		}
	} else if ($attr == 't') {
		$plantsTransplanted = getPlantsTransplanted ( $startTime, $endTime, $cropId );
		foreach ( $plantsTransplanted as $p ) {
			if (isset ( $result [$p ['startDate']] )) {
				$result [$p ['startDate']] += $p ['quantity'];
			} else {
				$result [$p ['startDate']] = $p ['quantity'];
			}
		}
	}
	return $result;
}
function getHarvestDailyCropData($startTime, $endTime, $cropId, $unitid) {
	$result = array ();
	$ans = getHarvests ( $startTime, $endTime, $cropId, $unitid );
	foreach ( $ans as $p ) {
		if (isset ( $result [$p ['startDate']] )) {
			$result [$p ['startDate']] += $p ['quantity'];
		} else {
			$result [$p ['startDate']] = $p ['quantity'];
		}
	}
	return $result;
}
function getSalesDailyCropData($startTime, $endTime, $cropId, $unitid, $customerid) {
	$result = array ();
	$ans = getSales ( $startTime, $endTime, $cropId, $unitid, $customerid );
	foreach ( $ans as $p ) {
		if (isset ( $result [$p ['startDate']] )) {
			$result [$p ['startDate']] += $p ['quantity'];
		} else {
			$result [$p ['startDate']] = $p ['quantity'];
		}
	}
	return $result;
}
function getDonationDailyCropData($startTime, $endTime, $cropId, $unitid, $customerid) {
	$result = array ();
	$ans = getDonation ( $startTime, $endTime, $cropId, $unitid, $customerid );
	foreach ( $ans as $p ) {
		if (isset ( $result [$p ['startDate']] )) {
			$result [$p ['startDate']] += $p ['quantity'];
		} else {
			$result [$p ['startDate']] = $p ['quantity'];
		}
	}
	return $result;
}
/**
 * Get crop data within a year, recorded by week. You don't need to call this function. Use getSingleYearWeeklyCropData() or 
 * getRangeWeeklyCropData() instead.
 * @param $year
 * four digit year
 * @param $startTime
 * start of range format= (yyyy-mm-dd)
 * @param $endTime
 * end of range. If this isn't in the same year as $startTime, WE WILL HAVE PROBLEMS, K?
 * @param $attr
 * attr = 's' or 'p' or 't', representing seedsbought/planted/transplanted
 * @return
 * An array $result[WeekStr] => value.
 * WeekStr is of the format mm/dd - mm/dd
 */
function _getGeneralWeeklyCropData($year, $startTime, $endTime, $cropId, $attr, $includeEmptyWeeks = false) {
	$firstSat = getFirstSat ( $year );
	$result = array ();
	if (attr == 's') {
		$ans = getSeedPurchases ( $startTime, $endTime, $cropId );
		foreach ( $ans as $s ) {
			$week = getWeekNumber ( $s ['startDate'], $firstSat );
			if (isset ( $result [$week] )) {
				$result [$week] += $s ['quantity'];
			} else {
				$result [$week] = $s ['quantity'];
			}
		}
	} elseif (attr == 'p') {
		$plantsAdded = getPlantsAdded ( $startTime, $endTime, $cropId );
		foreach ( $plantsAdded as $p ) {
			$week = getWeekNumber ( $p ['startDate'], $firstSat );
			if (isset ( $result [$week] )) {
				$result [$week] += $p ['quantity'];
			} else {
				$result [$week] = $p ['quantity'];
			}
		}
	} elseif (attr == 't') {
		$plantsTransplanted = getPlantsTransplanted ( $startTime, $endTime, $cropId );
		foreach ( $plantsTransplanted as $p ) {
			$week = getWeekNumber ( $p ['startDate'], $firstSat );
			if (isset ( $result [$week] )) {
				$result [$week] += $p ['quantity'];
			} else {
				$result [$week] = $p ['quantity'];
			}
		}
	}
	if (count ( $result ) == 0)
		return $result;
	
	if ($includeEmptyWeeks) {
		$keys = array_keys ( $result );
		$max = max ( $keys );
		$min = min ( $keys );
		for($i = $min + 1; $i < $max; $i ++) {
			if (! isset ( $result [$i] )) {
				$result [$i] = 0;
			}
		}
	}
	$result = mySort ( $result );
	$prettyResult = array ();
	foreach ( array_keys ( $result ) as $i ) {
		$j = $result [$i];
		$prettyResult [getWeekString ( $i, $year )] = $j;
	}
	return $prettyResult;
}
function _getHarvestWeeklyCropData($year, $startTime, $endTime, $cropId, $unitid, $includeEmptyWeeks = false) {
	$firstSat = getFirstSat ( $year );
	$result = array ();
	$ans = getHarvests ( $startTime, $endTime, $cropId, $unitid );
	foreach ( $ans as $s ) {
		$week = getWeekNumber ( $s ['startDate'], $firstSat );
		if (isset ( $result [$week] )) {
			$result [$week] += $s ['quantity'];
		} else {
			$result [$week] = $s ['quantity'];
		}
	}
	if (count ( $result ) == 0)
		return $result;
	
	if ($includeEmptyWeeks) {
		$keys = array_keys ( $result );
		$max = max ( $keys );
		$min = min ( $keys );
		for($i = $min + 1; $i < $max; $i ++) {
			if (! isset ( $result [$i] )) {
				$result [$i] = 0;
			}
		}
	}
	$result = mySort ( $result );
	$prettyResult = array ();
	foreach ( array_keys ( $result ) as $i ) {
		$j = $result [$i];
		$prettyResult [getWeekString ( $i, $year )] = $j;
	}
	return $prettyResult;
}
function _getSalesWeeklyCropData($year, $startTime, $endTime, $cropId, $unitid, $customerid, $includeEmptyWeeks = false) {
	$firstSat = getFirstSat ( $year );
	$result = array ();
		$ans = getSales ( $startTime, $endTime, $cropId, $unitid, $customerid );
		foreach ( $ans as $s ) {
			$week = getWeekNumber ( $s ['startDate'], $firstSat );
			if (isset ( $result [$week] )) {
				$result [$week] += $s ['quantity'];
			} else {
				$result [$week] = $s ['quantity'];
			}
		}
	if (count ( $result ) == 0)
		return $result;
	
	if ($includeEmptyWeeks) {
		$keys = array_keys ( $result );
		$max = max ( $keys );
		$min = min ( $keys );
		for($i = $min + 1; $i < $max; $i ++) {
			if (! isset ( $result [$i] )) {
				$result [$i] = 0;
			}
		}
	}
	$result = mySort ( $result );
	$prettyResult = array ();
	foreach ( array_keys ( $result ) as $i ) {
		$j = $result [$i];
		$prettyResult [getWeekString ( $i, $year )] = $j;
	}
	return $prettyResult;
}
function _getDonationWeeklyCropData($year, $startTime, $endTime, $cropId, $unitid, $customerid, $includeEmptyWeeks = false) {
	$firstSat = getFirstSat ( $year );
	$result = array ();
		$ans = getDonation ( $startTime, $endTime, $cropId, $unitid, $customerid );
		foreach ( $ans as $s ) {
			$week = getWeekNumber ( $s ['startDate'], $firstSat );
			if (isset ( $result [$week] )) {
				$result [$week] += $s ['quantity'];
			} else {
				$result [$week] = $s ['quantity'];
			}
		}
	if (count ( $result ) == 0)
		return $result;
	
	if ($includeEmptyWeeks) {
		$keys = array_keys ( $result );
		$max = max ( $keys );
		$min = min ( $keys );
		for($i = $min + 1; $i < $max; $i ++) {
			if (! isset ( $result [$i] )) {
				$result [$i] = 0;
			}
		}
	}
	$result = mySort ( $result );
	$prettyResult = array ();
	foreach ( array_keys ( $result ) as $i ) {
		$j = $result [$i];
		$prettyResult [getWeekString ( $i, $year )] = $j;
	}
	return $prettyResult;
}

/**
 * Get crop data within a range, recorded by week.
 * Start and End MUST BE THE SAME YEAR!!!!!!!!!!!!!!!!!!!!!
 * 
 * @param $startTime
 * start of range format= (yyyy-mm-dd)
 * @param $endTime
 * end of range. If this isn't in the same year as $startTime, WE WILL HAVE PROBLEMS, K?
 * @param $cropId
 * cropId at database
 * @param $tables
 * listing of attributes to return. If this is null, return all attributes possible. Current attributes are
 * 'harvests', 'seedPurchases', 'plantsAdded', 'plantsTransplanted', 'revenue', and 'quantitySold'
 * @return
 * a 2-dimentional array: $result[WeekStr][Type].
 * WeekStr is of the format mm/dd - mm/dd
 * Type can be 'harvests', 'seedPurchases', 'plantsAdded', 'plantsTransplanted', 'revenue', or 'quanititySold'
 */
function getGeneralRangeWeeklyCropData($startTime, $endTime, $cropId, $attr, $includeEmptyWeeks = false) {
	$year = substr ( $startTime, 0, 4 );
	if (strcmp ( $year, substr ( $endTime, 0, 4 ) ) != 0)
		return null;
	return _getGeneralWeeklyCropData ( $year, $startTime, $endTime, $cropId, $attr, $includeEmptyWeeks );
}
function getHarvestRangeWeeklyCropData($startTime, $endTime, $cropId, $unitid, $includeEmptyWeeks = false) {
	$year = substr ( $startTime, 0, 4 );
	if (strcmp ( $year, substr ( $endTime, 0, 4 ) ) != 0)
		return null;
	return _getHarvestWeeklyCropData ( $year, $startTime, $endTime, $cropId, $unitid, $includeEmptyWeeks );
}
function getSalesRangeWeeklyCropData($startTime, $endTime, $cropId, $unitid, $customerid, $includeEmptyWeeks = false) {
	$year = substr ( $startTime, 0, 4 );
	if (strcmp ( $year, substr ( $endTime, 0, 4 ) ) != 0)
		return null;
	return _getSalesWeeklyCropData ( $year, $startTime, $endTime, $cropId, $unitid, $customerid, $includeEmptyWeeks );
}
function getDonationRangeWeeklyCropData($startTime, $endTime, $cropId, $unitid, $customerid, $includeEmptyWeeks = false) {
	$year = substr ( $startTime, 0, 4 );
	if (strcmp ( $year, substr ( $endTime, 0, 4 ) ) != 0)
		return null;
	return _getDonationWeeklyCropData ( $year, $startTime, $endTime, $cropId, $unitid, $customerid, $includeEmptyWeeks );
}